<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="classificationName">
        <el-select v-model="queryParams.classificationName" placeholder="请输入分类名称">
          <el-option v-for="item in classificationName" :key="item" :label="item" :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品编码" prop="partsCode">
        <el-input v-model="queryParams.partsCode" placeholder="请输入产品编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="partsName">
        <el-input v-model="queryParams.partsName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-input v-model="queryParams.supplier" placeholder="请输入供应商" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:accessories:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:accessories:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:accessories:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:accessories:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accessoriesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="50" label="id" :index="indexMethod">
      </el-table-column>
      <el-table-column label="配件图片" align="center" prop="pictureUrl">
        <template v-slot="scope">
          <img class="tableImg" @click="UploadImg(scope.row.partsCode)" v-if="!scope.row.pictureUrl"
            src="../../../assets/images/unknown.png" />
          <img class="tableImg" v-else :src="addRandomParam(scope.row.pictureUrl)"
            @click="UploadImg1(scope.row.partsCode, scope.row.pictureUrl)" />
        </template>
      </el-table-column>
      <el-table-column label="产品编码" align="center" prop="partsCode" />
      <el-table-column label="产品名称" align="center" prop="partsName" />
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="规格" align="center" prop="partSpecifications" />
      <el-table-column label="型号" align="center" prop="partModel" />
      <el-table-column label="单价" align="center" prop="unitPrice" />
      <el-table-column label="单位" align="center" prop="partCompany" />
      <el-table-column label="分类名称" align="center" prop="classificationName" />
      <el-table-column label="车型" align="center" prop="busModelList">
        <template v-slot="scope">
          <span>{{ scope.row.busModelList.join(',') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="supplier" />
      <el-table-column label="制造厂" align="center" prop="manufacturer" />
      <el-table-column label="图件号" align="center" prop="drawingNo" />
      <el-table-column label="配件位置" align="center" prop="partsLocation" />
      <el-table-column label="配件架号" align="center" prop="frameNo" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:accessories:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:accessories:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改领料列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="formList">
        <el-row>
          <el-col :span="12" style="height:70px">
            <el-form-item label="车型" prop="busModelList">
              <el-input v-model="form.busModelList" placeholder="请输入车型" />
              <span style="color:red">新增/修改车型请用逗号分隔</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="classificationName">
              <el-select v-model="form.classificationName" placeholder="请输入分类名称">
                <el-option v-for="item in classificationName" :key="item" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品编码" prop="partsCode">
              <el-input v-model="form.partsCode" placeholder="请输入产品编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="partsName">
              <el-input v-model="form.partsName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="型号" prop="partModel">
              <el-input v-model="form.partModel" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="partSpecifications">
              <el-input v-model="form.partSpecifications" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="partCompany">
              <el-input v-model="form.partCompany" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制造厂" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入制造厂" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图件号" prop="drawingNo">
              <el-input v-model="form.drawingNo" placeholder="请输入图件号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-input v-model="form.supplier" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input v-model="form.unitPrice" placeholder="请输入单价" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="配件位置" prop="partsLocation">
              <el-input v-model="form.partsLocation" placeholder="请输入配件位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="配件架号" prop="frameNo">
              <el-input v-model="form.frameNo" placeholder="请输入配件架号" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :visible.sync="dialogVisible" class="DialogImg" :close-on-click-modal="false">
      <div class="ImgText2">配件图片上传</div>
      <el-upload :action="uploadAction" list-type="picture-card" :show-file-list="false"
        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
        <i class="el-icon-plus" v-if="this.dialogImageUrl == ''"></i>
        <img width="94%" v-else :src="dialogImageUrl" alt="">

      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="uploadNotarize">确 定</el-button>
        <el-button @click="uploadCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAccessories, getAccessories, delAccessories, addAccessories, updateAccessories, listMaintenance } from "@/api/system/accessories";

export default {
  name: "Accessories",
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 领料列表表格数据
      accessoriesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      classificationName: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        busModelList: null,
        classificationName: null,
        partsCode: null,
        partsName: null,
        partModel: null,
        partSpecifications: null,
        partCompany: null,
        manufacturer: null,
        brand: null,
        drawingNo: null,
        supplier: null,
        unitPrice: null,
        pictureUrl: null,
        partsLocation: null,
        frameNo: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        busModelList: [
          { required: true, message: '请输入车型', trigger: 'blur' }
        ],
        classificationName: [
          { required: true, message: '请选择分类名称', trigger: 'change' }
        ],
        partsCode: [
          { required: true, message: '请输入产品编码', trigger: 'blur' }
        ],
        partsName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        partModel: [
          { required: true, message: '请输入型号', trigger: 'blur' }
        ],
        partSpecifications: [
          { required: true, message: '请输入规格', trigger: 'blur' }
        ],
        partCompany: [
          { required: true, message: '请输入单位', trigger: 'blur' }
        ],
        manufacturer: [
          { required: true, message: '请输入制造厂', trigger: 'blur' }
        ],
        brand: [
          { required: true, message: '请输入品牌', trigger: 'blur' }
        ],
        drawingNo: [
          { required: true, message: '请输入图件号', trigger: 'blur' }
        ],
        supplier: [
          { required: true, message: '请输入供应商', trigger: 'blur' }
        ],
        unitPrice: [
          { required: true, message: '请输入单价', trigger: 'blur' }
        ],
        partsLocation: [
          { required: true, message: '请输入配件位置', trigger: 'blur' }
        ],
        frameNo: [
          { required: true, message: '请输入配件架号', trigger: 'blur' }
        ]
      },
      partsCode: '',
      file: {}

    };
  },
  created() {
    this.getList();
    this.listMaintenance();
  },
  computed: {
    // 人员列表序号
    indexMethod() {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + 1;
    },
    uploadAction() {
      return process.env.VUE_APP_BASE_API + '/minio/upload';
    }
  },
  methods: {
    addRandomParam(url) {
      // 生成一个随机参数，确保每次加载图片时都是一个新的URL
      return url + `?random=${Math.random()}`;
    },
    listMaintenance() {
      listMaintenance().then(rst => {
        if (rst.code === 200) {
          this.classificationName = rst.rows.map(item => item.classificationName);
        }
      })
    },
    /** 查询领料列表列表 */
    getList() {
      this.loading = true;
      listAccessories(this.queryParams).then(response => {
        this.accessoriesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        busModelList: null,
        classificationName: null,
        partsCode: null,
        partsName: null,
        partModel: null,
        partSpecifications: null,
        partCompany: null,
        manufacturer: null,
        brand: null,
        drawingNo: null,
        supplier: null,
        unitPrice: null,
        pictureUrl: null,
        partsLocation: null,
        frameNo: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加领料列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAccessories(id).then(response => {
        this.form = response.data;
        this.form.busModelList = response.data.busModelList.join(',');
        this.open = true;
        this.title = "修改领料列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (this.form.busModelList.includes(',')) {
              this.form.busModelList = this.form.busModelList.split(',');
            } else {
              this.form.busModelList = [this.form.busModelList];
            }
            updateAccessories(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
            this.form.busModelList = this.form.busModelList.join(',');
          } else {
            if (this.form.busModelList.includes(',')) {
              this.form.busModelList = this.form.busModelList.split(',');
            } else {
              this.form.busModelList = [this.form.busModelList];
            }
            addAccessories(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();

            });
            this.form.busModelList = this.form.busModelList.join(',');
          }
        }
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除领料列表编号为"' + ids + '"的数据项？').then(function () {
        return delAccessories(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/accessories/export', {
        ...this.queryParams
      }, `accessories_${new Date().getTime()}.xlsx`)
    },
    // 配件图片上传
    handleAvatarSuccess(res, file) {
      this.form.pictureUrl = URL.createObjectURL(file.raw);
      this.dialogImageUrl = URL.createObjectURL(file.raw);
      // 在成功上传后调用成功函数
      // 这里可以添加您希望执行的逻辑
    },
    beforeAvatarUpload(file) {
      this.file = file;
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }

      // 返回true表示允许上传
      return isJPG && isLt2M;
    },
    UploadImg(partsCode) {
      this.dialogVisible = true;
      this.partsCode = partsCode;
    },
    UploadImg1(partsCode, pictureUrl) {
      this.dialogVisible = true;
      this.partsCode = partsCode;
      this.dialogImageUrl = pictureUrl + `?random=${Math.random()}`;
    },

    uploadNotarize() {

      const fileName = this.partsCode + '.jpg';
      const formData = new FormData();
      formData.append('file', this.file);
      formData.append('fileName', fileName);

      const axios = require('axios');
      axios.post(process.env.VUE_APP_BASE_API + '/minio/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
        .then(response => {
          if (response.status == 200) {
            this.dialogVisible = false;
            this.dialogImageUrl = '';
            this.getList();
          }
        })
        .catch(error => {
          // 处理错误
          console.error(error);
        });



    },
    uploadCancel() {
      this.dialogVisible = false;
      this.dialogImageUrl = '';
      this.getList();
    }
  }
};
</script>
<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;

}

::v-deep .el-dialog__body {
  padding-left: 10px !important;
}

.formList {
  ::v-deep .el-input__inner {
    width: 300px;
  }
}

.tableImg {
  width: 80px;
  height: 80px;
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

::v-deep .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.ImgText {
  color: red;
}

.DialogImg {

  // position: relative;
  ::v-deep .el-upload {
    width: 250px;
    height: 250px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  ::v-deep .el-dialog__body {
    display: flex;
    justify-content: center;
  }

  ::v-deep .el-icon-plus {
    font-size: 55px;
  }

  .ImgText2 {
    position: absolute;
    left: 20px;
    top: 20px;
    font-weight: 800;
  }
}
</style>
